package com.neusoft.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * @author cpx
 * @date 2024/11/6
 * @Description
 */
@Service
public class TokenUtil {
    @Value("${application.jwt.secret-key}")
    private String secretKey;

    @Value("${application.jwt.expire-time}")
    private Long expiration;
    //生成token
    public String toToken(String userId) {
        return Jwts.builder()
                .setSubject(userId)
                .signWith(getSignKey())
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
//                .claim("email",userName)
                .compact();
    }
    //解析token获取用户id
    public String getSub(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(getSignKey())
                    .build()
                    .parseClaimsJws(token);
            return claimsJws.getBody().getSubject();
        } catch (JwtException e) {
            return null;
        }
    }
    //校验token是否过期
    public boolean validateToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(getSignKey())
                    .build()
                    .parseClaimsJws(token);

            Date now = new Date(System.currentTimeMillis());
            Date expiration = claimsJws.getBody().getExpiration();
            return expiration.after(now);
        } catch (JwtException e) {
            return false;
        }
    }

    private Key getSignKey() {
        return Keys.hmacShaKeyFor(secretKey.getBytes());
    }
}
